#include "gui_frame.h"

GuiFrame::GuiFrame( Widget* _parent, Engine* _engine, const QString& _title,
                    int _x, int _y, int _w, int _h, int openingTime )
    :Widget( _parent, _engine, _x, _y, _w, _h ),
    blackPen( Qt::black ),
    invisibleBrush( QColor( 255, 255, 255, 100 ), Qt::SolidPattern )
{
    title = _title;

    QFont f( "Palatino", 10 );
    QFontMetrics fm( f );
    ascent = fm.ascent();
    descent = fm.descent();
    titleWidth = fm.width( "  " + title + "  " );    // <-- horrible but needed

    opening = new Animation( engine->fps, openingTime );
    oRect = new OpeningRect( opening, 0.5, 0, openingTime * 0.7 );
    ct = new ColorTransition( opening, QColor( 255, 255, 255, 0 ), QColor( 255, 255, 255, 255 ),
                              ColorTransition::AllChannels, openingTime * 0.7 , openingTime );
    opening->AddObserver( this );
    engine->AddAnimation( opening );

    mouseTracking = true;
}

GuiFrame::~GuiFrame( void )
{
    engine->RemoveAnimation( opening );
    delete oRect;
    delete ct;
    delete opening;
}

void GuiFrame::doShow( void )
{
    paintEnabled = true;
    opening->Stop();
    opening->Play();
}

void GuiFrame::doHide( void )
{
    visible = false;
    opening->Reverse( true );
    opening->Play();
}

void GuiFrame::Paint( QPainter &painter )
{
    painter.setPen( blackPen );
    painter.setBrush( invisibleBrush );
    painter.drawRoundedRect( x + oRect->x * w,
                             y + ascent + oRect->y * ( h - ascent ),
                             w * oRect->w,
                             h * oRect->h, 3, 3 );

    if( title != "" )
    {
        QColor tColor;
        ct->GetColor( tColor );
        painter.setPen( Qt::NoPen );
        painter.setBrush( QBrush( tColor, Qt::SolidPattern ) );
        painter.drawRect( x + 10, y, titleWidth, ascent + descent + 1 );

        painter.setPen( QColor( 0, 0, 0, ct->a ) );
        painter.drawText( x + 12, y + ascent, title );
    }
}

void GuiFrame::OnPause(Animation* a)
{
    ;
}

void GuiFrame::OnStop(Animation* a)
{
    ;
}

void GuiFrame::OnEnd(Animation* a)
{
    if( !a->IsReversed() )
    {
        visible = true;
        Showed();
    }
    else
    {
        paintEnabled = false;
        Hidden();
    }
}

void GuiFrame::OnPlay(Animation* a)
{
    ;
}
